<template>
  <a-drawer
    title="After-Sale Details"
    :open="open"
    @close="handleClose"
    :width="drawerWidth"
    class="after-sale-detail-drawer"
    :destroyOnClose="true"
  >
    <template v-if="afterSaleDetail">
      <!-- 商品信息 -->
      <div class="product-info">
        <div class="product-card">
          <div class="product-image">
            <img :src="afterSaleDetail.detail?.image" alt="Product image" />
          </div>
          <div class="product-details">
            <div class="product-name">{{ afterSaleDetail.detail?.goods_name }}</div>
            <div class="product-spec">
              Specification: 
              <template v-if="afterSaleDetail.detail?.spec">
                <template v-if="parseSpecText(afterSaleDetail.detail.spec).size">
                  {{ parseSpecText(afterSaleDetail.detail.spec).size }}
                </template>
                <template v-if="parseSpecText(afterSaleDetail.detail.spec).imageUrl">
                  <span class="color-image-container" v-if="parseSpecText(afterSaleDetail.detail.spec).imageUrl">
                    <img :src="parseSpecText(afterSaleDetail.detail.spec).imageUrl" alt="color" class="color-image"/>
                  </span>
                </template>
                <template v-if="!parseSpecText(afterSaleDetail.detail.spec).size && !parseSpecText(afterSaleDetail.detail.spec).imageUrl">
                  {{ afterSaleDetail.detail.spec}}
                </template>
              </template>
            </div>
            <div class="product-price">
              <span>Price: ¥{{ afterSaleDetail.detail?.price }}</span>
              <span class="quantity">Quantity: {{ afterSaleDetail.detail?.num }}</span>
            </div>
          </div>
        </div>
      </div>

      <a-divider />

      <!-- 售后信息 -->
      <div class="after-sale-info">
        <a-descriptions title="After-Sale Information" bordered>
          <a-descriptions-item label="After-Sale Type" :span="3">
            {{ afterSaleDetail.refund_type === 1 ? 'Return and Refund' : 'Exchange' }}
          </a-descriptions-item>
          <a-descriptions-item label="Apply Quantity" :span="3">
            {{ afterSaleDetail.refund_num }}
          </a-descriptions-item>
          <a-descriptions-item label="Apply Amount" :span="3">
            ¥{{ afterSaleDetail.apply_money }}
          </a-descriptions-item>
          <a-descriptions-item label="Apply Reason" :span="3">
            {{ afterSaleDetail.remark_type }}
          </a-descriptions-item>
          <a-descriptions-item label="Apply Description" :span="3">
            {{ afterSaleDetail.remark }}
          </a-descriptions-item>
          <a-descriptions-item label="Apply Proof" :span="3">
            <div class="image-list" v-if="afterSaleDetail.remark_images">
              <img 
                v-for="(img, index) in afterSaleDetail.remark_images.split(',')" 
                :key="index" 
                :src="img" 
                @click="previewImage(img)"
                class="preview-image"
              />
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="Apply Time">
            <DateFormatter :value="afterSaleDetail.create_time" />
          </a-descriptions-item>
        </a-descriptions>
      </div>

      <a-divider />

      <!-- 处理进度 -->
      <div class="process-info">
        <a-descriptions title="Process Progress" bordered>
          <a-descriptions-item label="Audit Status" :span="3">
            <a-tag :color="getAuditStatusColor(afterSaleDetail.audit_status)">
              {{ getAuditStatusText(afterSaleDetail.audit_status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="Refuse Reason" :span="3" v-if="afterSaleDetail.audit_status === 3">
            {{ afterSaleDetail.refuse_reason }}
          </a-descriptions-item>
          <a-descriptions-item label="Refund Amount" :span="3" v-if="afterSaleDetail.refund_money > 0">
            ¥{{ afterSaleDetail.refund_money }}
          </a-descriptions-item>
          <a-descriptions-item label="Refund Freight" :span="3" v-if="afterSaleDetail.refund_freight > 0">
            ¥{{ afterSaleDetail.refund_freight }}
          </a-descriptions-item>
        </a-descriptions>
      </div>

      <!-- 审核通过时显示物流信息填写表单 -->
      <template v-if="afterSaleDetail.audit_status === 2 && !afterSaleDetail.user_ship_status">
        <a-divider />
        <div class="logistics-form">
          <a-descriptions title="Fill in Logistics Information" bordered>
            <a-descriptions-item label="Logistics Company" :span="3">
              <a-select
                v-model:value="logisticsForm.delivery_company_id"
                placeholder="Please select a logistics company"
                style="width: 100%"
                :loading="loadingCompanies"
                @change="handleCompanyChange"
              >
                <a-select-option
                  v-for="company in logisticsCompanies"
                  :key="company.id"
                  :value="company.id"
                  :name="company.name"
                >
                  {{ company.name }}
                </a-select-option>
              </a-select>
            </a-descriptions-item>
            <a-descriptions-item label="Logistics No" :span="3">
              <a-input v-model:value="logisticsForm.delivery_no" placeholder="Please enter the logistics number" />
            </a-descriptions-item>
            <a-descriptions-item label="Operation" :span="3">
              <a-button type="primary" @click="submitLogisticsInfo" :loading="submitting">
                提交物流信息
              </a-button>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>

      <!-- 物流信息 -->
      <template v-if="afterSaleDetail.user_ship_status === 1">
        <a-divider />
        <div class="logistics-info">
          <a-descriptions title="Logistics Information" bordered>
            <a-descriptions-item label="Shipment Status" :span="3">
              <a-tag color="green">已发货</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="Shipment Time" :span="3">
              {{ formatTime(afterSaleDetail.user_ship_time) }}
            </a-descriptions-item>
            <a-descriptions-item label="Logistics Information" :span="3" v-if="afterSaleDetail.user_ship_delivery">
              <div class="delivery-info">
                <div>Logistics Company: {{ afterSaleDetail.user_ship_delivery.delivery_company }}</div>
                <div>Logistics No: {{ afterSaleDetail.user_ship_delivery.delivery_no }}</div>
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>

      <!-- 商家收货信息 -->
      <template v-if="afterSaleDetail.receive_status === 1">
        <a-divider />
        <div class="receive-info">
          <a-descriptions title="Merchant Receipt Information" bordered>
            <a-descriptions-item label="Receipt Status" :span="3">
              <a-tag color="green">已收货</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="Receipt Time" :span="3">
              {{ formatTime(afterSaleDetail.receive_time) }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>

      <!-- 换货物流信息 -->
      <template v-if="afterSaleDetail.refund_type === 2 && afterSaleDetail.exchange_delivery">
        <a-divider />
        <div class="exchange-info">
          <a-descriptions title="Exchange Logistics Information" bordered>
            <a-descriptions-item label="Logistics Company" :span="3">
              {{ afterSaleDetail.exchange_delivery.company }}
            </a-descriptions-item>
            <a-descriptions-item label="Logistics No" :span="3">
              {{ afterSaleDetail.exchange_delivery.no }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>

      <!-- 售后地址 -->
      <template v-if="afterSaleDetail.refund_address">
        <a-divider />
        <div class="refund-address">
          <a-descriptions title="After-Sale Address" bordered>
            <a-descriptions-item label="Recipient" :span="3">
              {{ afterSaleDetail.refund_address.name }}
            </a-descriptions-item>
            <a-descriptions-item label="Phone Number" :span="3">
              {{ afterSaleDetail.refund_address.phone }}
            </a-descriptions-item>
            <a-descriptions-item label="Full Address" :span="3">
              {{ afterSaleDetail.refund_address.full_address }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>

      <!-- 商家售后地址 -->
      <template v-if="afterSaleDetail.merchant_address">
        <a-divider />
        <div class="merchant-address">
          <a-descriptions title="Merchant After-Sale Address" bordered>
            <a-descriptions-item label="Recipient" :span="3">
              {{ afterSaleDetail.merchant_address.name }}
            </a-descriptions-item>
            <a-descriptions-item label="Phone Number" :span="3">
              {{ afterSaleDetail.merchant_address.phone }}
            </a-descriptions-item>
            <a-descriptions-item label="Full Address" :span="3">
              {{ afterSaleDetail.merchant_address.address }}
            </a-descriptions-item>
          </a-descriptions>
        </div>
      </template>
    </template>
  </a-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { getLogisticsCompany, submitAfterSaleLogistics } from '@/api/user';
import DateFormatter from '@/components/common/DateFormatter.vue';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  afterSaleDetail: {
    type: Object,
    default: null
  },
  isLogin: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:open']);

// Add window width tracking
const windowWidth = ref(window.innerWidth);
const drawerWidth = computed(() => {
  if (windowWidth.value <= 576) {
    return '100%';
  } else if (windowWidth.value <= 768) {
    return '85%';
  } else {
    return '600px';
  }
});

// Add window resize handler
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener('resize', handleResize);

  if (!props.isLogin) {
    fetchLogisticsCompanies();
  }
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

// 解析规格文本
const parseSpecText = (specText) => {
  if (!specText) return { size: '', imageUrl: '' };
  
  if (specText.includes('http') && specText.includes('，')) {
    const parts = specText.split('，');
    return {
      imageUrl: parts[0],
      size: parts[1] || ''
    };
  }
  
  if (specText.includes('http')) {
    return {
      imageUrl: specText,
      size: ''
    };
  }
  
  return {
    imageUrl: '',
    size: specText
  };
};

// 获取审核状态颜色
const getAuditStatusColor = (status) => {
  const colorMap = {
    1: 'orange',
    2: 'green',
    3: 'red'
  };
  return colorMap[status] || 'default';
};

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const textMap = {
    1: 'Pending Audit',
    2: 'Approved',
    3: 'Rejected'
  };
  return textMap[status] || 'Unknown Status';
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString();
};

// 预览图片
const previewImage = (url) => {
  Modal.info({
    title: 'Image Preview',
    content: `<img src="${url}" style="max-width: 100%;" />`,
    icon: null,
    width: '80%',
    maskClosable: true
  });
};

const handleClose = () => {
  emit('update:open', false);
};

// 物流公司列表
const logisticsCompanies = ref([]);
const loadingCompanies = ref(false);

// 获取物流公司列表
const fetchLogisticsCompanies = async () => {
  try {
    loadingCompanies.value = true;
    const res = await getLogisticsCompany();
    if (res.code === 200) {
      logisticsCompanies.value = res.result || [];
    } else {
      message.error(res.message || 'Failed to get logistics company list');
    }
  } catch (error) {
    console.error('Failed to get logistics company list:', error);
    message.error('Failed to get logistics company list, please try again later');
  } finally {
    loadingCompanies.value = false;
  }
};

// 物流信息表单
const logisticsForm = ref({
  delivery_company: '',      // 物流公司名称
  delivery_company_id: '',   // 物流公司ID
  delivery_no: '',          // 物流单号
  id: ''                    // 售后单ID
});
const submitting = ref(false);

// 处理物流公司选择
const handleCompanyChange = (value, option) => {
  console.log('Selected company:', option); // 添加日志
  logisticsForm.value.delivery_company = option.name;
  logisticsForm.value.delivery_company_id = value; // 使用选中的值作为ID
  console.log('Updated logistics form:', logisticsForm.value); // 添加日志
};

// 提交物流信息
const submitLogisticsInfo = async () => {
  if (!logisticsForm.value.delivery_company) {
    message.warning('Please select a logistics company');
    return;
  }
  if (!logisticsForm.value.delivery_no) {
    message.warning('Please enter the logistics number');
    return;
  }

  try {
    submitting.value = true;
    const res = await submitAfterSaleLogistics({
      id: props.afterSaleDetail.id,
      delivery_company: logisticsForm.value.delivery_company,
      delivery_company_id: logisticsForm.value.delivery_company_id,
      delivery_no: logisticsForm.value.delivery_no
    });
    
    if (res.code === 200) {
      message.success('Logistics information submitted successfully');
      // 关闭抽屉
      handleClose();
      // 触发刷新事件
      emit('refresh');
    } else {
      message.error(res.message || 'Failed to submit logistics information');
    }
  } catch (error) {
    console.error('Failed to submit logistics information:', error);
    message.error('Failed to submit logistics information, please try again later');
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.after-sale-detail-drawer {
  width: 100%;
  max-width: 100%;
}

.product-info {
  margin-bottom: 16px;
}

.product-card {
  display: flex;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 12px;
  background-color: #fafafa;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-weight: bold;
  margin-bottom: 6px;
  color: #333;
  font-size: 14px;
  word-break: break-word;
}

.product-spec {
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.product-price {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
  flex-wrap: wrap;
}

.quantity {
  margin-left: 12px;
}

.color-image-container {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  overflow: hidden;
  margin-left: 8px;
  border: 1px solid #eee;
  vertical-align: middle;
  flex-shrink: 0;
}

.color-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.preview-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.preview-image:hover {
  transform: scale(1.05);
}

.delivery-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* Responsive styles */
@media (max-width: 768px) {
  .product-card {
    flex-direction: column;
  }
  
  .product-image {
    margin-bottom: 12px;
    margin-right: 0;
    width: 60px;
    height: 60px;
  }
  
  .preview-image {
    width: 60px;
    height: 60px;
  }
}

@media (max-width: 576px) {
  .product-spec, .product-price {
    font-size: 11px;
  }
  
  .preview-image {
    width: 50px;
    height: 50px;
  }
}

.logistics-form {
  margin: 16px 0;
}

.logistics-form :deep(.ant-input) {
  width: 100%;
}

.logistics-form :deep(.ant-btn) {
  margin-top: 8px;
}
</style> 